// Background Service Worker

console.log('AI Crawler Assistant 后台服务已启动');

// 当前执行的任务状态（全局变量，不会因popup关闭而丢失）
let currentExecutingTask = null;

/**
 * 执行任务（核心逻辑，从popup.js迁移过来）⭐⭐⭐
 */
async function handleExecuteTask(taskId, sendResponse) {
  console.log(`\n[Background] ========== 开始执行任务 ${taskId} ==========`);
  
  if (currentExecutingTask) {
    console.log('[Background] ⚠️ 已有任务正在执行，请稍后');
    sendResponse({ success: false, error: '已有任务正在执行' });
    return;
  }
  
  currentExecutingTask = { taskId, status: 'running', startTime: Date.now() };
  
  try {
    // 1. 获取设置
    const settings = await chrome.storage.sync.get({ backendUrl: 'http://localhost:8080' });
    const apiBaseUrl = settings.backendUrl + '/api';
    
    // 2. 获取待执行的问句列表
    console.log(`[Background] 请求URL: ${apiBaseUrl}/collect-tasks/${taskId}/pending-questions`);
    
    const response = await fetch(`${apiBaseUrl}/collect-tasks/${taskId}/pending-questions`);
    const result = await response.json();
    
    console.log('[Background] 待执行问句API响应:', result);
    
    if (result.code !== 200) {
      throw new Error(result.message || '获取待执行问句失败');
    }
    
    const { taskName, pendingQuestions } = result.data;
    
    console.log('[Background] 任务名称:', taskName);
    console.log('[Background] 待执行问句数量:', pendingQuestions ? pendingQuestions.length : 0);
    
    if (!pendingQuestions || pendingQuestions.length === 0) {
      console.log('[Background] 任务已全部完成');
      currentExecutingTask = null;
      sendResponse({ success: true, message: '任务已全部完成' });
      return;
    }
    
    const totalQuestions = pendingQuestions.length;
    
    // 3. 循环执行每个问句
    for (let i = 0; i < totalQuestions; i++) {
      const question = pendingQuestions[i];
      const { questionId, questionContent, pendingPlatforms } = question;
      
      console.log(`\n[Background] ========== 问句 ${i + 1}/${totalQuestions} ==========`);
      console.log(`[Background] 问句ID: ${questionId}`);
      console.log(`[Background] 问句内容: ${questionContent}`);
      console.log(`[Background] 待执行平台: ${pendingPlatforms.join(', ')}`);
      
      if (!questionId || !questionContent || !Array.isArray(pendingPlatforms) || pendingPlatforms.length === 0) {
        console.error('[Background] ❌ 问句数据不完整，跳过');
        continue;
      }
      
      // 4. 循环执行每个平台
      for (let platformIndex = 0; platformIndex < pendingPlatforms.length; platformIndex++) {
        const platform = pendingPlatforms[platformIndex];
        
        console.log(`\n[Background] ========== [${platformIndex + 1}/${pendingPlatforms.length}] 执行平台: ${platform} ==========`);
        console.log(`[Background] 时间: ${new Date().toLocaleTimeString()}`);
        
        try {
          // 采集
          const startTime = Date.now();
          console.log(`[Background] 🚀 开始采集...`);
          
          const collectResult = await collectQuestionFromPlatform(questionId, questionContent, platform);
          
          const responseTime = Date.now() - startTime;
          console.log(`[Background] ✅ 采集完成，耗时 ${responseTime}ms`);
          console.log(`[Background] 采集结果:`, {
            hasResponse: !!collectResult.response,
            hasAnswer: !!(collectResult.response && collectResult.response.answer),
            answerLength: collectResult.response && collectResult.response.answer ? collectResult.response.answer.length : 0
          });
          
          // 上报结果
          const responseData = collectResult.response || collectResult;
          
          console.log(`[Background] 🚀 开始上报结果...`);
          await submitResultToBackend(taskId, questionId, platform, {
            questionContent,
            answerContent: responseData.answer || '',
            answerHtml: responseData.answerHtml || responseData.answer || '',
            responseTime,
            collectStatus: 'success'
          }, settings.backendUrl);
          
          console.log(`[Background] ✅ ${platform} 采集成功并上报`);
          
        } catch (error) {
          console.error(`[Background] ❌ ${platform} 采集失败:`, error);
          
          // 上报失败状态
          try {
            await submitResultToBackend(taskId, questionId, platform, {
              questionContent,
              collectStatus: 'failed',
              errorMessage: error.message || error.toString()
            }, settings.backendUrl);
            console.log(`[Background] ✅ 失败状态已上报`);
          } catch (reportError) {
            console.error(`[Background] ❌ 上报失败状态也失败:`, reportError);
          }
        }
        
        console.log(`[Background] ⏭️ [${platformIndex + 1}/${pendingPlatforms.length}] 平台处理完成`);
      }
      
      console.log(`[Background] ⏭️⏭️ 问句 ${i + 1}/${totalQuestions} 执行完成\n`);
    }
    
    // 5. 完成
    console.log('[Background] ========== 任务执行完成 ==========');
    currentExecutingTask = null;
    sendResponse({ success: true, message: '任务执行完成' });
    
  } catch (error) {
    console.error('[Background] 任务执行失败:', error);
    currentExecutingTask = null;
    sendResponse({ success: false, error: error.message });
  }
}

/**
 * 从指定平台采集问句
 */
async function collectQuestionFromPlatform(questionId, questionContent, platform) {
  console.log(`\n[Background] [collectQuestionFromPlatform] 开始`);
  console.log(`[Background]   平台: ${platform}`);
  console.log(`[Background]   问句ID: ${questionId}`);
  
  // 查找对应平台的标签页
  const tabs = await chrome.tabs.query({});
  const platformUrls = {
    'deepseek': 'chat.deepseek.com',
    'yuanbao': 'yuanbao.tencent.com',
    'doubao': 'doubao.com'
  };
  
  const platformTab = tabs.find(tab => 
    tab.url && tab.url.includes(platformUrls[platform])
  );
  
  if (!platformTab) {
    console.error(`[Background]   ❌ 未找到${platform}平台的标签页`);
    throw new Error(`未找到${platform}平台的标签页，请先打开对应页面`);
  }
  
  console.log(`[Background]   ✅ 找到${platform}标签页 ID: ${platformTab.id}`);
  
  // 激活标签页
  try {
    console.log(`[Background]   激活标签页...`);
    await chrome.tabs.update(platformTab.id, { active: true });
    console.log(`[Background]   ✅ 标签页已激活`);
    await new Promise(resolve => setTimeout(resolve, 1000));  // 等待1秒
  } catch (error) {
    console.error(`[Background]   ❌ 激活标签页失败:`, error);
    throw new Error(`激活${platform}标签页失败: ${error.message}`);
  }
  
  // 发送消息给content script
  return new Promise((resolve, reject) => {
    const taskId = currentExecutingTask ? currentExecutingTask.taskId : 0;
    
    console.log(`[Background]   📤 发送消息给content script...`);
    
    // 超时保护（3分钟）
    let hasResponded = false;
    const timeoutId = setTimeout(() => {
      if (!hasResponded) {
        console.error(`[Background]   ❌ 超时：3分钟内未收到响应`);
        hasResponded = true;
        reject(new Error(`${platform}平台采集超时（3分钟）`));
      }
    }, 180000);
    
    chrome.tabs.sendMessage(platformTab.id, {
      action: 'sendMessage',
      message: questionContent,
      taskId: taskId,
      questionId: questionId
    }, (response) => {
      if (hasResponded) return;
      
      clearTimeout(timeoutId);
      hasResponded = true;
      
      console.log(`[Background]   📥 收到响应:`, response);
      
      if (chrome.runtime.lastError) {
        console.error(`[Background]   ❌ lastError:`, chrome.runtime.lastError.message);
        reject(new Error(chrome.runtime.lastError.message));
        return;
      }
      
      if (response && response.success) {
        console.log(`[Background]   ✅ 响应成功`);
        resolve(response);
      } else {
        console.error(`[Background]   ❌ 响应失败:`, response);
        reject(new Error(response ? response.error : '采集失败'));
      }
    });
    
    console.log(`[Background]   ✅ sendMessage已调用，等待响应...`);
  });
}

/**
 * 上报结果到后端
 */
async function submitResultToBackend(taskId, questionId, platform, result, backendUrl) {
  const apiUrl = backendUrl + '/api/collect/submit';
  
  const data = {
    taskId,
    questionId,
    questionContent: result.questionContent,
    platform,
    answerContent: result.answerContent || '',
    answerHtml: result.answerHtml || '',
    collectTime: new Date().toISOString(),
    responseTime: result.responseTime || 0,
    collectStatus: result.collectStatus || 'success',
    errorMessage: result.errorMessage || null
  };
  
  console.log(`[Background] 上报到后端:`, {
    taskId,
    questionId,
    platform,
    answerLength: data.answerContent.length
  });
  
  const response = await fetch(apiUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data)
  });
  
  const responseResult = await response.json();
  
  if (responseResult.code !== 200) {
    throw new Error(responseResult.message || '上报失败');
  }
  
  console.log(`[Background] ✅ 上报成功`);
  return responseResult;
}

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log('[Background] 收到消息:', message.action);
  
  switch (message.action) {
    case 'executeTask':
      // ⭐⭐⭐ 新增：执行任务（在background执行，不受popup影响）⭐⭐⭐
      handleExecuteTask(message.taskId, sendResponse);
      return true; // 保持消息通道打开
      
    case 'sendToMultiplePlatforms':
      handleSendToMultiplePlatforms(message, sendResponse);
      return true; // 保持消息通道打开
      
    case 'batchSend':
      handleBatchSend(message);
      sendResponse({ success: true });
      return false;
      
    default:
      sendResponse({ success: false, error: 'Unknown action' });
      return false;
  }
});

// 处理多平台发送
async function handleSendToMultiplePlatforms(message, sendResponse) {
  const { message: text, platforms } = message;
  const results = [];
  
  for (let i = 0; i < platforms.length; i++) {
    const platform = platforms[i];
    
    try {
      console.log(`[Background] 处理平台 ${i + 1}/${platforms.length}: ${platform}`);
      
      const result = await sendToPlatform(platform, text);
      results.push({ platform, success: true, ...result });
      
      console.log(`[Background] ${platform} 发送成功`);
      
      // 关键：等待一段时间让自动采集完成
      // 等待时间 = 预估AI响应时间 + 稳定检测时间
      if (i < platforms.length - 1) {
        // 从设置读取延迟时间
        const settings = await chrome.storage.sync.get({ platformSwitchDelay: 8 });
        const delaySeconds = settings.platformSwitchDelay;
        
        console.log(`[Background] 等待 ${delaySeconds} 秒让 ${platform} 采集完成...`);
        await sleep(delaySeconds * 1000);
      }
      
    } catch (e) {
      console.error(`[Background] ${platform} 失败:`, e);
      results.push({ platform, success: false, error: e.message });
    }
  }
  
  const allSuccess = results.every(r => r.success);
  sendResponse({ 
    success: allSuccess, 
    results,
    error: allSuccess ? null : '部分平台发送失败'
  });
}

// 处理批量发送
async function handleBatchSend(message) {
  const { messages, platforms } = message;
  
  for (let i = 0; i < messages.length; i++) {
    const text = messages[i];
    
    for (let j = 0; j < platforms.length; j++) {
      const platform = platforms[j];
      
      try {
        console.log(`[Background] 批量任务 ${i + 1}/${messages.length} - 平台 ${j + 1}/${platforms.length}: ${platform}`);
        
        await sendToPlatform(platform, text);
        
        // 通知进度
        chrome.runtime.sendMessage({
          action: 'batchProgress',
          current: i * platforms.length + j + 1,
          total: messages.length * platforms.length
        });
        
        // 等待AI响应和采集完成
        const settings = await chrome.storage.sync.get({ platformSwitchDelay: 8 });
        const delaySeconds = settings.platformSwitchDelay;
        
        console.log(`[Background] 等待 ${delaySeconds} 秒让 ${platform} 响应和采集...`);
        await sleep(delaySeconds * 1000);
        
      } catch (e) {
        console.error(`[Background] 发送到 ${platform} 失败:`, e);
      }
    }
    
    // 每个问题之间额外延迟
    if (i < messages.length - 1) {
      console.log('[Background] 等待进入下一个问题...');
      await sleep(2000);
    }
  }
  
  console.log('[Background] 批量任务全部完成');
}

// 发送消息到指定平台
async function sendToPlatform(platform, text) {
  const platformUrls = {
    'deepseek': 'https://chat.deepseek.com/',
    'yuanbao': 'https://yuanbao.tencent.com/',
    'doubao': 'https://www.doubao.com/'
  };
  
  const url = platformUrls[platform];
  if (!url) {
    throw new Error(`未知平台: ${platform}`);
  }
  
  console.log(`[Background] 准备发送到 ${platform}`);
  
  // 查找目标标签页
  const tabs = await chrome.tabs.query({});
  const hostname = new URL(url).hostname;
  
  // 找到所有匹配的标签页
  const matchingTabs = tabs.filter(tab => tab.url && tab.url.includes(hostname));
  
  let targetTab = null;
  
  if (matchingTabs.length === 0) {
    // 没有找到，创建新标签页
    console.log(`[Background] 未找到 ${platform} 标签页，创建新的`);
    targetTab = await chrome.tabs.create({ url, active: true });
    
    // 等待页面加载和content script注入
    await sleep(5000);
  } else if (matchingTabs.length === 1) {
    // 只有一个，使用它
    targetTab = matchingTabs[0];
    console.log(`[Background] 找到 ${platform} 标签页:`, targetTab.id);
  } else {
    // 有多个，优先使用激活的，或最近访问的
    targetTab = matchingTabs.find(tab => tab.active) || matchingTabs[matchingTabs.length - 1];
    console.log(`[Background] 找到多个标签页，使用:`, targetTab.id);
  }
  
  // 关键：激活标签页（确保在前台）
  await chrome.tabs.update(targetTab.id, { active: true });
  console.log(`[Background] 已激活标签页:`, targetTab.id);
  
  // 等待标签页激活
  await sleep(500);
  
  // 聚焦窗口
  await chrome.windows.update(targetTab.windowId, { focused: true });
  
  // 再等待一下确保窗口激活
  await sleep(300);
  
  // 发送消息到content script
  console.log(`[Background] 发送消息到content script...`);
  
  return new Promise((resolve, reject) => {
    chrome.tabs.sendMessage(
      targetTab.id,
      { action: 'sendMessage', text },
      (response) => {
        if (chrome.runtime.lastError) {
          console.error(`[Background] 发送失败:`, chrome.runtime.lastError);
          reject(new Error(chrome.runtime.lastError.message));
        } else if (response && response.success) {
          console.log(`[Background] 发送成功`);
          resolve(response);
        } else {
          console.error(`[Background] 响应错误:`, response);
          reject(new Error(response?.error || '发送失败'));
        }
      }
    );
  });
}

// 工具函数：延迟
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// 监听安装事件
chrome.runtime.onInstalled.addListener((details) => {
  if (details.reason === 'install') {
    console.log('首次安装插件');
    
    // 初始化默认设置
    chrome.storage.sync.set({
      backendUrl: 'http://localhost:8080',
      autoCollect: true,
      syncToBackend: true
    });
    
    // 初始化统计数据
    chrome.storage.local.set({
      todayCount: 0,
      totalCount: 0,
      cachedData: [],
      lastDate: new Date().toDateString()
    });
    
    // 打开欢迎页面
    chrome.tabs.create({
      url: 'https://github.com/yourusername/ai-crawler-extension'
    });
  }
});

// 每天重置今日统计
chrome.alarms.create('resetDailyStats', {
  when: getNextMidnight(),
  periodInMinutes: 24 * 60
});

chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === 'resetDailyStats') {
    chrome.storage.local.get(['todayCount', 'totalCount'], (result) => {
      chrome.storage.local.set({
        todayCount: 0,
        lastDate: new Date().toDateString()
      });
    });
  }
});

function getNextMidnight() {
  const now = new Date();
  const midnight = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate() + 1,
    0, 0, 0
  );
  return midnight.getTime();
}

